package com.rz.htk.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rz.core.exception.GlobalException;
import com.rz.htk.dubbo.service.AdminService;
import com.rz.htk.order.entity.Order;
import com.rz.htk.order.entity.OrderHis;
import com.rz.htk.order.entity.OrderRecord;
import com.rz.htk.order.mapper.OrderHisMapper;
import com.rz.htk.order.mapper.OrderRecordMapper;
import com.rz.htk.order.service.IOrderHisService;
import com.rz.htk.order.service.IOrderRecordService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrderHisServiceImpl extends ServiceImpl<OrderHisMapper,OrderHis> implements IOrderHisService{

    @Resource
    AdminService adminService;
    @Override
    public IPage<OrderHis> getPage(OrderHis orderHis) {
        QueryWrapper<OrderHis> wrapper = buildWrapper(orderHis);
        wrapper.orderByDesc("id");
        Page<OrderHis> page = new Page<>(orderHis.getPageNo(), orderHis.getPageSize());
        IPage<OrderHis> desktopIPage = page(page, wrapper);
        return desktopIPage;
    }


    private QueryWrapper<OrderHis> buildWrapper(OrderHis orderHis){
        QueryWrapper<OrderHis> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(orderHis.getCommodityCode())) {
            wrapper.eq("commodity_code", orderHis.getCommodityCode());
        }
        if (StringUtils.isNotEmpty(orderHis.getAfterCode())) {
            wrapper.eq("after_code", orderHis.getAfterCode());
        }

        //小于
        if (StringUtils.isNotEmpty(orderHis.getEndTime())) {
            wrapper.lt("creation_time", orderHis.getEndTime());
        }
        //大于
        if (StringUtils.isNotEmpty(orderHis.getStartTime())) {
            wrapper.gt("creation_time", orderHis.getStartTime());
        }
        List<Integer> mngID = adminService.getChildrenIds(orderHis.getCrteMngId());
        mngID.add(orderHis.getCrteMngId());
        wrapper.in("crte_mng_id",mngID);

        return wrapper;
    }


    @Override
    public boolean saveOrderHis(Order order,Integer delMngId,Integer state) {
        OrderHis orderHis = new OrderHis();
        BeanUtils.copyProperties(order,orderHis);
        orderHis.setState(state);
        orderHis.setHisTime(LocalDateTime.now());
        orderHis.setDelMngId(delMngId);
        boolean isOk = this.save(orderHis);
        if (!isOk) {
            throw new GlobalException("订单移除失败！");
        }
        return isOk;
    }
}

